package com.tenglong.teacher.ui.adapter.viewholder;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.StudentSignHeaderInfo;
import com.tenglong.teacher.data.resultInfo.BaseStudentSignInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.StudentAdapter;
import com.tenglong.teacher.ui.adapter.viewholder.base.BaseViewHolder;
import com.tenglong.teacher.ui.dialog.ExitDialog;
import com.tenglong.teacher.ui.dialog.PictureDialogFragment;
import com.tenglong.teacher.ui.homepage.FragmentHompage;
import com.tenglong.teacher.ui.homepage.PublishHomeworkActivity;
import com.tenglong.teacher.ui.utils.MyUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class StudentSignHeaderViewHolder extends BaseViewHolder<BaseStudentSignInfo> implements View.OnClickListener {
    private boolean isClass = true;
    private StudentAdapter.StudentListener listener;
    private TextView className, lessonName, time, classOver, studentSignNum, batchHandle;
    private StudentSignHeaderInfo data;
    private View publishBook;
    private Context mContext;

    public StudentSignHeaderViewHolder(View itemView) {
        super(itemView);
        this.mContext = itemView.getContext();
    }

    public StudentSignHeaderViewHolder(View itemView, StudentAdapter.StudentListener listener) {
        this(itemView);
        this.listener = listener;
        if (listener != null) {
            isClass = listener.getClassType().equals(FragmentHompage.TYPE_ALL_CLASS);
        }
        initView();
        setListener();
    }

    private void setListener() {
        batchHandle.setOnClickListener(this);
        classOver.setOnClickListener(this);
        publishBook.setOnClickListener(this);
    }

    private void initView() {
        className = itemView.findViewById(R.id.className);
        lessonName = itemView.findViewById(R.id.lessonName);
        time = itemView.findViewById(R.id.time);
        classOver = itemView.findViewById(R.id.classOver);
        studentSignNum = itemView.findViewById(R.id.studentSignNum);
        batchHandle = itemView.findViewById(R.id.batchHandle);
        publishBook = itemView.findViewById(R.id.publishBook);
    }

    @Override
    public void setLayoutInfo(BaseStudentSignInfo info) {
        data = (StudentSignHeaderInfo) info;
        className.setText(data.className + "(" + data.courseName + ")");
        lessonName.setText("第" + data.classNum + "次课");
        time.setText(data.time);
        classOver.setText(data.isClassBeing ? "下课" : "上课");
        ((ViewGroup) studentSignNum.getParent()).setVisibility(Integer.valueOf(data.stuNum) == 0 ? View.GONE : (isClass ? View.VISIBLE : View.GONE));
        if (isClass && ((ViewGroup) studentSignNum.getParent()).getVisibility() == View.VISIBLE) {
            String text = "学员数" + data.stuNum + ",请假" + data.leaveNumber + ",实到" + data.attendance;
            SpannableStringBuilder builder = new SpannableStringBuilder(text);
            builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.theme_green)), 3, 4 + (data.stuNum + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.theme_green)), 6 + (data.stuNum + "").length(), 7 + (data.stuNum + "").length() + (data.leaveNumber + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.theme_green)), 9 + (data.stuNum + "").length() + (data.leaveNumber + "").length(), 9 + (data.stuNum + "").length() + (data.leaveNumber + "").length()
                    + (data.attendance + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            studentSignNum.setText(builder);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.batchHandle:
                if (Integer.valueOf(data.stuNum) == 0) {
                    ToastUtils.showCenterToast("还没有学生！");
                    return;
                }
                if (listener != null) {
                    listener.onBatchOperation(getLayoutPosition());
                }
                break;
            case R.id.classOver:
                if (Integer.valueOf(data.stuNum) == 0) {
                    ToastUtils.showCenterToast("还没有学生！");
                    return;
                }
                if (listener != null) {
                    if (!data.isClassBeing) {
                        toClassOverwithNull();
                    } else {
                        if (isClass) {
                            if (listener.getSignState()) {
                                if (data.isHomeWorkState) {
                                    toClassOverwithNull();
                                } else {
                                    toShowIsClassOverDialog();
                                }
                            } else {
                                ToastUtils.showCenterToast("请给学生签到后重试");
                            }
                        } else {
                            if (listener.getSignState()) {
                                if (data.isHomeWorkState) {
                                    toClassOverWithPagerCertificate();
                                } else {
                                    toShowIsClassOverDialog();
                                }
                            } else {
                                ToastUtils.showCenterToast("请给学生签到后重试");
                            }
                        }
                    }
                }
                break;
            case R.id.publishBook:
                if (Integer.valueOf(data.stuNum) == 0) {
                    ToastUtils.showCenterToast("还没有学生！");
                    return;
                }
//                if (!data.isClassBeing) {
//                    ToastUtils.showCenterToast("上课后再可布置作业");
//                    return;
//                }

//                if (data.homeWorkStatu == 2) {
//                    ToastUtils.showCenterToast("已有 " + data.submitCount + " 名学生提交作业，无法再次发布");
//                    return;
//                }

//                if (data.homeWorkStatu == 3) {
//                    ToastUtils.showCenterToast("作业已截止，无法再次发布");
//                    return;
//                }
                if (listener != null) {
                    Intent intent = new Intent(mContext, PublishHomeworkActivity.class);
                    intent.putExtra(MyUtils.CLASSID, listener.getClassId());
                    ((Activity) mContext).startActivityForResult(intent, GlobalConstant.REQUEST_CODE_PUBLISH_HOMEWORK_ACTIVITY);
                }
                break;
        }
    }

    private void toShowIsClassOverDialog() {
        ExitDialog.getExitDialog(isClass ? "还没有布置作业，确定下课？" : "还没有布置作业,是否上传纸质证明后下课？").setExitListener(new ExitDialog.ExitListener() {
            @Override
            public void onExit(boolean exitState) {
                if (exitState) {
                    if (isClass) {
                        toClassOver();
                    } else {
                        getImage();
                    }
                }
            }
        }).show(((FragmentActivity) mContext).getSupportFragmentManager(), "toClassOver");
    }

    private void toClassOverWithPagerCertificate() {
        ExitDialog.getExitDialog("请上传纸质证明！").setExitListener(new ExitDialog.ExitListener() {
            @Override
            public void onExit(boolean exitState) {
                if (exitState) {
                    getImage();
                }
            }
        }).show(((FragmentActivity) mContext).getSupportFragmentManager(), "withPagerDialog");
    }

    private void getImage() {
        PictureDialogFragment.getInstance().setPictureDialogListener(new PictureDialogFragment.PictureDialogListener() {
            @Override
            public void onPhotoAlbum() {
                listener.toPhotoAlbum();
            }

            @Override
            public void onShoot() {
                listener.toShoot();
            }

            @Override
            public void onCancle() {
            }
        }).show(((FragmentActivity) mContext).getSupportFragmentManager(), "picture");
    }

    private void toClassOverwithNull() {
        ExitDialog.getExitDialog(data.isClassBeing ? "确定下课？" : "确定开始上课？").setExitListener(new ExitDialog.ExitListener() {
            @Override
            public void onExit(boolean exitState) {
                if (exitState) {
                    toClassOver();
                }
            }
        }).show(((FragmentActivity) mContext).getSupportFragmentManager(), "dialog");
    }

    private void toClassOver() {
        final ProgressDialog mProgressDlg = new ProgressDialog(itemView.getContext());
        mProgressDlg.setMessage("正在访问,请稍后...");
        mProgressDlg.setCanceledOnTouchOutside(false);
        mProgressDlg.show();
        CreateRequestEntity.getWebService().classOverOrUp(data.id, data.isClassBeing ? "1" : "0", DataState.getInstance().getUserInfo().getId()).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                mProgressDlg.dismiss();
                if (ResultVerifier.isSucceed(response)) {
                    ((Activity) mContext).setResult(Activity.RESULT_OK, new Intent().putExtra(GlobalConstant.RESULT_CODE_STUDENT_SIGN_ACTIVITY, !data.isClassBeing));
                    classOver.setText(data.isClassBeing ? "上课" : "下课");
                    ToastUtils.showCenterToast(data.isClassBeing ? "下课请求成功" : "上课请求成功");
                    if (data.isClassBeing) {
                        ((Activity) mContext).finish();
                    } else {
                        if (listener != null) {
                            listener.onClickClassBegin(getLayoutPosition(), true);
                        }
                        data.classStartTime = response.body().data;
                        if (listener != null) {
                            listener.getPublishHomeWorkState();
                        }
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                mProgressDlg.dismiss();
                ResultVerifier.systerErrers(t);
            }
        });
    }
}
